﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Weixin.Core.config
{
    /// <summary>
    /// IP工具类
    /// 用于获取内外网IP
    /// 验证IP有效性
    /// 获取IP值,可取地区范围
    /// 获取真实IP及代理IP
    /// </summary>
    public static class IPUtils
    {

        /// <summary>
        /// 外网IP标识
        /// </summary>
        public const int W_IP = 1;

        /// <summary>
        /// 局域网IP标识
        /// </summary>
        public const int L_IP = 0;


        /// <summary>
        /// 获取真实IP地址
        /// 对果对方使用多层代理，则获取最后一层代理IP
        ///  HTTP_X_FORWARDED_FOR 可以伪造，不再信任HTTP_X_FORWARDED_FOR
        /// </summary>
        public static string IPRealAddress
        {
            get
            {
                //如果有X-Real-IP就取这个IP为客户端IP for Nginx
                HttpRequest Request = HttpContext.Current.Request; // ForumContext.Current.Context.Request;
                string x_Real_IP = Request.ServerVariables["HTTP_X_REAL_IP"];
                if (!string.IsNullOrEmpty(x_Real_IP))
                {
                    return x_Real_IP;
                }
                else
                {
                    // HTTP_X_FORWARDED_FOR 容易伪造，所以不再信任HTTP_X_FORWARDED_FOR这个头信息,直接获取REMOTE_ADDR
                    //if (string.IsNullOrEmpty(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
                    string userIP = Request.ServerVariables["REMOTE_ADDR"];
                    //else
                    //  userIP = getFirstIPFromProxy(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
                    if (string.IsNullOrEmpty(userIP))
                        userIP = Request.UserHostAddress;
                    return userIP;
                }
            }
        }


    }
}
